package com.hdcx.Minfresh.activity;

import android.app.AlertDialog;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.bean.CartWrapper;
import com.hdcx.Minfresh.bean.DetailWrapper;
import com.hdcx.Minfresh.bean.UserInfoBean;
import com.hdcx.Minfresh.model.Statue;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.util.GsonUtils;
import com.hdcx.Minfresh.util.ShpfUtil;
import com.hdcx.Minfresh.view.GlideImageLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/18.
 */

public class DetailActivity extends BaseActivity {
    String id;
    Banner banner;
    TextView tv_title1, tv_short_title, tv_price, tv_volume, tv_yieldly, tv_etalon, tv_num, tv_cart_num;
    WebView webview;
    int num;//库存
    int ps = 0;//配送
    int is_score = 0;//积分
    int is_special;//是否抢购商品
    String is_special_tips;//抢购商品提示
    ImageView img_collect, img_dong;
    TextView tv_collect, tv_kucun;
    TranslateAnimation animation;
    private TextView mTextViewXianGou;
    private Button mBt_go;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_detail);
        initView();
        initData();
    }

    private void initView() {
        mTextViewXianGou = (TextView) findViewById(R.id.textViewXianGou);
        banner = (Banner) findViewById(R.id.banner);
        tv_title1 = (TextView) findViewById(R.id.tv_title1);
        tv_short_title = (TextView) findViewById(R.id.tv_short_title);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_volume = (TextView) findViewById(R.id.tv_volume);
        tv_yieldly = (TextView) findViewById(R.id.tv_yieldly);
        tv_etalon = (TextView) findViewById(R.id.tv_etalon);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_cart_num = (TextView) findViewById(R.id.tv_cart_num);
        tv_kucun = (TextView) findViewById(R.id.tv_kucun);
        webview = (WebView) findViewById(R.id.webview);
        findViewById(R.id.img_jia).setOnClickListener(this);
        findViewById(R.id.img_jian).setOnClickListener(this);
     /*   findViewById(R.id.img_collect).setOnClickListener(this);*/
        img_collect = (ImageView) findViewById(R.id.img_collect);
        img_dong = (ImageView) findViewById(R.id.img_dong);
        tv_collect = (TextView) findViewById(R.id.tv_collect);
//        img_collect.setOnClickListener(this);
//        tv_collect.setOnClickListener(this);
     /*   findViewById(R.id.tv_collect).setOnClickListener(this);*/
        mBt_go = (Button) findViewById(R.id.bt_go);
        mBt_go.setOnClickListener(this);
        findViewById(R.id.tv_left).setOnClickListener(this);
        ((TextView) findViewById(R.id.tv_title)).setText("详情");
        findViewById(R.id.img_cart).setOnClickListener(this);
        animation = (TranslateAnimation) AnimationUtils.loadAnimation(this, R.anim.right_to_left);
        findViewById(R.id.rela_collect).setOnClickListener(this);
    }

    private void initData() {
        id = getIntent().getStringExtra("id");
        Log.e("DetailActivity", "DetailActivity--initData--传过来的ID"+id);
        post_main();
    }

    /*  id		//产品id
      ps   //配送日期   可选  默认0*/
    private void post_main() {
        AppUtil.showLoading(this);
//        if (AppUtil.need_to_login(this)) {
//            return;
//        }
        JSONObject json = new JSONObject();
        UserInfoBean user = ShpfUtil.getObject(ShpfUtil.LOGIN);
        Log.e("DetailActivity", "DetailActivity--post_main--1111111111");
        try {
            if (user == null) {
                json.put("uid", "0");
            } else {
                json.put("uid", user.getUserinfo().getId());
            }
            json.put("id", id);
            json.put("ps", ps);

        } catch (JSONException e) {
            Log.e("DetailActivity", "DetailActivity--post_main--22222222");
            e.printStackTrace();
        }
        Log.e("DetailActivity", "DetailActivity--post_main--33333333333");
        OkHttpUtils.postString()
                .url(MyUrl.GITEM)
                .content(json.toString())
                .build()
                .execute(new Callback<DetailWrapper>() {
                    @Override
                    public DetailWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        Log.e("DetailActivity", "DetailActivity--parseNetworkResponse--商品详情" + json);
                        return new Gson().fromJson(json, DetailWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("DetailActivity", "DetailActivity--onError--4444444");
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(DetailWrapper response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            setValue(response);
                        }
                    }
                });
    }

    /*  uid		//用户id
    // gid		//产品id*/

    private void add() {
        JSONObject json = new JSONObject();
        AppUtil.showLoading(this);
        UserInfoBean user = ShpfUtil.getObject(ShpfUtil.LOGIN);
        try {
            json.put("uid", user.getUserinfo().getId());
            json.put("gid", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.ADDCOLLECT)
                .content(json.toString())
                .build()
                .execute(new Callback<DetailWrapper>() {
                    @Override
                    public DetailWrapper parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, DetailWrapper.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(DetailWrapper response) {
                        AppUtil.closeLoading();
                        Toast.makeText(DetailActivity.this, response.getInfo(), Toast.LENGTH_SHORT).show();
                        if (response.getStatus() == 1) {
                            img_collect.setImageResource(R.drawable.green_start);
                            tv_collect.setText("已收藏");
                        } else if (response.getStatus() == 2) {
                            img_collect.setImageResource(R.drawable.star);
                            tv_collect.setText("加入收藏");
                        }

                    }
                });
    }

    private void setValue(DetailWrapper response) {
        List<String> imgs = new ArrayList<>();
        for (int i = 0; i < response.getGinfo().getPiclist().size(); i++) {
            imgs.add(response.getGinfo().getPiclist().get(i).getImg());
        }
        banner.setImages(imgs);
        banner.setImageLoader(new GlideImageLoader());
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.start();
        AppUtil.showPic(imgs.get(0), img_dong);
        tv_title1.setText(response.getGinfo().getTitle());
        tv_short_title.setText(response.getGinfo().getShort_title());
        tv_price.setText("￥" + response.getGinfo().getPrice() + "/" + response.getGinfo().getUnits());
        tv_etalon.setText("规格：" + response.getGinfo().getEtalon());

        String market_price = response.getGinfo().getMarket_price();
        if (Double.parseDouble(market_price) > 0) {
            tv_volume.setText("市场价：¥ " + market_price);
            tv_volume.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
            tv_volume.setVisibility(View.VISIBLE);
        } else {
            tv_volume.setVisibility(View.GONE);
        }
        tv_yieldly.setText("产地：" + response.getGinfo().getYieldly());
        webview.loadUrl(response.getGinfo().getContent());
        num = response.getGinfo().getQuantity();
        tv_kucun.setText("库存：" + num);
        if (num==0){
            tv_kucun.setText("已售罄");
            mBt_go.setText("已售罄");
            mBt_go.setEnabled(false);
        }else {
            tv_kucun.setVisibility(View.INVISIBLE);
        }
        if (response.getCollect() == 1) {
            img_collect.setImageResource(R.drawable.green_start);
            tv_collect.setText("已收藏");
        }
        is_special = response.getGinfo().getIs_specail();
        is_special_tips = response.getGinfo().getIs_specail_tips();
        if (is_special == 1) {
            mTextViewXianGou.setVisibility(View.VISIBLE);
            mTextViewXianGou.setText(is_special_tips);
        } else {
            mTextViewXianGou.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_jia:
                if (is_special == 1) {
                    Toast.makeText(DetailActivity.this, is_special_tips, Toast.LENGTH_SHORT).show();
                    Log.e("DetailActivity", "DetailActivity--onClick--特价");
                    return;
                }
                if (Integer.valueOf(tv_num.getText().toString()) + 1 > num  ){
                    Toast.makeText(DetailActivity.this, "库存不足", Toast.LENGTH_SHORT).show();
                    return;
                }
                int temp = Integer.valueOf(tv_num.getText().toString()) + 1 > num ? num : Integer.valueOf(tv_num.getText().toString()) + 1;
                tv_num.setText(temp + "");
                break;
            case R.id.img_cart:
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.img_jian:
                int temp2 = Integer.valueOf(tv_num.getText().toString());
                temp2 = temp2 <= 1 ? 1 : --temp2;
                tv_num.setText(temp2 + "");
                break;
//            case R.id.img_collect:
//                add();
//                break;
//            case R.id.tv_collect:
//                add();
//                break;
            case R.id.rela_collect:
                add();
                break;
            case R.id.bt_go:
                if (AppUtil.need_to_login(this)) {
                    return;
                }
                if (num <= 0) {
                    new AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("库存不足")
                            .setPositiveButton("是", null)
                            .create()
                            .show();
                    return;
                }

                JSONObject json = new JSONObject();
                AppUtil.showLoading(this);
                OkHttpUtils.postString()
                        .url(MyUrl.ISSHOPING)
                        .content(json.toString())
                        .build()
                        .execute(new Callback<String>() {
                            @Override
                            public String parseNetworkResponse(Response response) throws IOException {
                                String json = response.body().string();
                                return json;
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                                AppUtil.closeLoading();
                            }

                            @Override
                            public void onResponse(String response) {
                                AppUtil.closeLoading();
                                Statue statue = GsonUtils.parseJSON(response, Statue.class);
                                int status = statue.getStatus();
                                if (status == 1) {
                                    UserInfoBean user = ShpfUtil.getObject(ShpfUtil.LOGIN);
                                    CartWrapper carts = getCartById(user.getUserinfo().getId());
                                    if (carts == null) {
                                        carts = new CartWrapper();
                                    }
                                    img_dong.startAnimation(animation);
                                    //carts.setData(id, Integer.valueOf(tv_num.getText().toString()), ps, is_score, num);
                                    carts.setDataAdd(id, Integer.valueOf(tv_num.getText().toString()), ps, is_score, num);
                                    ShpfUtil.setObject(user.getUserinfo().getId(), carts);
                                    setCart_Num(user.getUserinfo().getId());
                                    AppUtil.setMain_Cart();
                                } else {
                                    new AlertDialog.Builder(DetailActivity.this)
                                            .setMessage(statue.getInfo())
                                            .setPositiveButton("是", null)
                                            .create()
                                            .show();
                                }
                            }
                        });
                break;
            case R.id.tv_left:
                AppUtil.setMain_Cart();
                finish();
                break;
        }
    }

    private void setCart_Num(String id) {
        CartWrapper cartWrapper = ShpfUtil.getObject(id);
        if (cartWrapper == null) {
            return;
        } else {
            int temp = 0;
            for (int i = 0; i < cartWrapper.carts.size(); i++) {
                temp = temp + cartWrapper.carts.get(i).num;
            }
            if (temp != 0) {
                tv_cart_num.setVisibility(View.VISIBLE);
                tv_cart_num.setText("" + (temp >= 100 ? 99 : temp));
            }
        }
    }


    public CartWrapper getCartById(String id) {
        //UserInfoBean user =  ShpfUtil.getObject(ShpfUtil.LOGIN);
        CartWrapper cartWrapper = ShpfUtil.getObject(id);
        return cartWrapper;
    }
}
